import React from "react";

import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import { BrowserRouter as Router, Link } from 'react-router-dom';//
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Divider from "antd/lib/divider";
import Row from "antd/lib/row";
import Table from "antd/lib/table";
import Menu from "antd/lib/menu";
import Dropdown from "antd/lib/dropdown";
import ConfigProvider from "antd/lib/config-provider";
import Layout from "antd/lib/layout";
import AutoComplete from "antd/lib/auto-complete";
import zhCN from 'antd/es/locale/zh_CN';
import { createBrowserHistory } from 'history'
import Enums from "@/services/enums";
import { currentUser } from "@/services/auth";
import routes from "@/services/routes";
import notification from "@/services/notification";

import moment from "moment";
import Workflow from "@/services/workflow";
import QueryShowField from "@/services/queryshowfield";
import { AppstoreFilled, DownOutlined, UpOutlined } from "@ant-design/icons";
import CreateQueryShowFieldDialog from "@/components/enums/QueryShowFieldDialog";
import CheckDialog from "@/components/workflow/CheckDialog";
import Customer from "@/services/customer";
import EmployeeActivityDialog from "@/components/employee/EmployeeActivityDialog";
import ProjectDetail from "@/services/projectdetail";
import Project from "@/services/project";
import DatePicker from "antd/lib/date-picker";
import locale from 'antd/es/date-picker/locale/zh_CN';
const customHistory = createBrowserHistory();

const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}

class ProjectToolBar extends React.Component {
  state = {
    page: 1,
    pagesize: localStorage.getItem("projecttoolbarpagesize") ? (localStorage.getItem("projecttoolbarpagesize") !== undefined ? Number(localStorage.getItem("projecttoolbarpagesize")) : 20) : 20,
    total: 1,
    order: 1,
    loading: false,
    code: localStorage.getItem("projecttoolbarcode") ? (localStorage.getItem("projecttoolbarcode") !== undefined ? localStorage.getItem("projecttoolbarcode") : '') : '',
    name: localStorage.getItem("projecttoolbarname") ? (localStorage.getItem("projecttoolbarname") !== undefined ? localStorage.getItem("projecttoolbarname") : '') : '',
    major: localStorage.getItem("projecttoolbarmajor") ? (localStorage.getItem("projecttoolbarmajor") !== undefined ? localStorage.getItem("projecttoolbarmajor") : '') : '',
    area: localStorage.getItem("projecttoolbararea") ? (localStorage.getItem("projecttoolbararea") !== undefined ? localStorage.getItem("projecttoolbararea") : '') : '',
    bytstatus: localStorage.getItem("projecttoolbarbytstatus") ? (localStorage.getItem("projecttoolbarbytstatus") !== undefined ? localStorage.getItem("projecttoolbarbytstatus") : '') : '',
    certificate: localStorage.getItem("projecttoolbarcertificate") ? (localStorage.getItem("projecttoolbarcertificate") !== undefined ? localStorage.getItem("projecttoolbarcertificate") : '') : '',
    location: localStorage.getItem("projecttoolbarlocation") ? (localStorage.getItem("projecttoolbarlocation") !== undefined ? localStorage.getItem("projecttoolbarlocation") : '') : '',
    strcustomername: localStorage.getItem("projecttoolbarstrcustomername") ? (localStorage.getItem("projecttoolbarstrcustomername") !== undefined ? localStorage.getItem("projecttoolbarstrcustomername") : '') : '',
    representative: localStorage.getItem("projecttoolbarrepresentative") ? (localStorage.getItem("projecttoolbarrepresentative") !== undefined ? localStorage.getItem("projecttoolbarrepresentative") : '') : '',
    genjindate:[],
    data: [],
    projectstatusdata: [],
    employeemajordata: [],
    employeecertificatedata: [],
    employeeareadata: [],
    queryshowfielddata: [],
    selectedrowkeys: [],
    selectedrows: [],
    employeeuserdata: [],
    showall: false,
    difference: "1",
  };
  componentWillMount() {
    Enums.items("employeestatus").then(data => {
      this.setState({
        employeestatusdata: data,
      });
    });
    Enums.items("employeemajor").then(data => {
      this.setState({
        employeemajordata: data,
      });
    });
    Enums.items("employeecertificate").then(data => {
      this.setState({
        employeecertificatedata: data,
      });
    });
    Enums.items("employeearea").then(data => {
      this.setState({
        employeeareadata: data,
      });
    });
    Customer.querycustomeruser({ code: "", name: "", userid: currentUser.id, }).then(data => {
      this.setState({
        employeeuserdata: data,
      });
    });
    this.fieldsshowload(this.state.difference);
    let param = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      major: this.state.major,
      area: this.state.area,
      bytstatus: this.state.bytstatus,
      certificate: this.state.certificate,
      location: this.state.location,
      strcustomername: this.state.strcustomername,
      representative: this.state.representative,
      userid: currentUser.id,
      id: 0,
      datadown: false,
      difference: this.state.difference,
    }
    this.seldata(param);
  }
  fieldsshowload = (difference) => {
    if (difference === "1") {
      QueryShowField.getbycode("projecttoolbar1").then(data => {
        this.setState({
          queryshowfielddata: data,
          difference: difference,
        });
      });
    } else {
      QueryShowField.getbycode("projecttoolbar2").then(data => {
        this.setState({
          queryshowfielddata: data,
          difference: difference,
        });
      });
    }
  }
  isEmptyobj = (str) => {
    if (str === '' || str === null || str === 'null' || str === undefined || str === 'undefined') {
      return true;
    } else {
      return false;
    }
  }
  seldata = (params = {}) => {
    if(!this.isEmptyobj(this.state.genjindate)){
      if(this.state.genjindate.length===2){
        params.genjinbegindate=this.state.genjindate[0].format('YYYY-MM-DD');
        params.genjinenddate=this.state.genjindate[1].format('YYYY-MM-DD');
      }
    }
    if (params.datadown) {
      if (this.state.data.length < 1) {
        notification.error("没有要导出的数据");
        return;
      }
      let AjaxUrl = 'api/projectdetailemployee/list';
      if (params.difference === "1") {
        AjaxUrl = 'api/project/list';
      }
      fetch(AjaxUrl, {
        method: 'POST',
        body: window.JSON.stringify(params),
        credentials: 'include',
        headers: new Headers({
          'Content-Type': 'application/json'
        })
      }).then((response) => {
        response.blob().then(blob => {
          const aLink = document.createElement('a');
          document.body.appendChild(aLink);
          aLink.style.display = 'none';
          const objectUrl = window.URL.createObjectURL(blob);
          aLink.href = objectUrl;
          aLink.download = '项目人员信息.xlsx';
          aLink.click();
          document.body.removeChild(aLink);
        });
      }).catch((error) => {
        window.console.log(error);
      });
    }
    else {
      this.setState({ loading: true });
      if (params.difference === "2") {
        ProjectDetail.getemployeelist(params).then(data => {
          this.setState({
            loading: false,
            data: data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
            field: params.field,
            order: params.order,
          });
        });
      }else{
        Project.getlist(params).then(data => {
          this.setState({
            loading: false,
            data: data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
            field: params.field,
            order: params.order,
          });
        });
      }
    }
  };

  handlesel = (index) => {
    let datadown = false;
    if (index === 2) {
      datadown = true;
    }
    let param = {
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      major: this.state.major,
      area: this.state.area,
      bytstatus: this.state.bytstatus,
      certificate: this.state.certificate,
      location: this.state.location,
      strcustomername: this.state.strcustomername,
      representative: this.state.representative,
      userid: currentUser.id,
      id: 0,
      datadown: datadown,
      difference: this.state.difference,
    }
    this.seldata(param);
  };
  handleTableChange = (pagination, filters, sorter) => {
    localStorage.setItem("projecttoolbarpagesize", pagination.pageSize);
    let field = sorter.field;
    let order = 0;
    if (sorter.order === "descend") {
      order = 1;
    }
    let param = {
      field: field,
      order: order,
      page: pagination.current,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      major: this.state.major,
      area: this.state.area,
      bytstatus: this.state.bytstatus,
      certificate: this.state.certificate,
      location: this.state.location,
      strcustomername: this.state.strcustomername,
      representative: this.state.representative,
      userid: currentUser.id,
      id: 0,
      datadown: false,
      difference: this.state.difference,
    }
    this.seldata(param);
  };
  handleCheck = (record) => {
    if (!currentUser.isAudit) {
      notification.error("没有权限.");
      return;
    }

    const item = {
      bill: "projectdetail",
      billtype: 0,
      billid: record.id,
      next_type: 1,
      message: '<div>同意</div>',
      userid: currentUser.id,
      billdate: moment().format('YYYY-MM-DD'),
      orgunitid: record.orgunitid,
      status: record.status,
    }
    let param = {
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      major: this.state.major,
      area: this.state.area,
      bytstatus: this.state.bytstatus,
      certificate: this.state.certificate,
      location: this.state.location,
      strcustomername: this.state.strcustomername,
      representative: this.state.representative,
      userid: currentUser.id,
      id: 0,
      datadown: false,
      difference: this.state.difference,
    }
    if (record.status === 0) {
      Workflow.check(item).then(data => {
        if (data[0].flag === 0) {
          notification.success(data[0].message);
          this.seldata(param);
        } else {
          notification.error(data[0].message);
        }
      })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    } else {
      CheckDialog.showModal({ bill_check: item })
        .onClose((result = {}) => {
          if (result.success) {
            this.seldata(param);
          }
        }).onDismiss(() => {
        });
    }
  }
  handleclear = () => {
    this.setState({
      code: "",
      name: "",
      major: "",
      area: "",
      bytstatus: "",
      certificate: "",
      location: "",
      strcustomername: "",
      representative: "",
    });
    localStorage.setItem("projecttoolbarcode", "");
    localStorage.setItem("projecttoolbarname", "");
    localStorage.setItem("projecttoolbarmajor", "");
    localStorage.setItem("projecttoolbararea", "");
    localStorage.setItem("projecttoolbarbytstatus", "");
    localStorage.setItem("projecttoolbarcertificate", "");
    localStorage.setItem("projecttoolbarlocation", "");
    localStorage.setItem("projecttoolbarstrcustomername", "");
    localStorage.setItem("projecttoolbarrepresentative", "");
  }
  handlefieldshow = () => {
    CreateQueryShowFieldDialog.showModal({ queryshowfield: this.state.queryshowfielddata })
      .onClose((result = {}) => {
        if (result.success) {
          this.fieldsshowload(this.state.difference);
        }
      }).onDismiss(() => {
      });
  }
  handleactivityshow = (record) => {
    EmployeeActivityDialog.showModal({ sourceid: record.id, sourcetype: "project", canedit: true })
      .onClose((result = {}) => {
      }).onDismiss(() => {
      });
  };
  onDragEnter = info => {
    window.console.log(info);
  };
  rowSelection() {
    const _this = this;
    const props = {
      onChange(newSelectedRowKeys, newSselectedRows) {
        _this.setState({
          selectedrows: newSselectedRows,
          selectedrowkeys: newSelectedRowKeys,
        });
      },
    };
    return props;
  };
  tabsClick = e => {
    this.fieldsshowload(e.key);
    let param = {
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      major: this.state.major,
      area: this.state.area,
      bytstatus: this.state.bytstatus,
      certificate: this.state.certificate,
      location: this.state.location,
      strcustomername: this.state.strcustomername,
      representative: this.state.representative,
      userid: currentUser.id,
      id: 0,
      datadown: false,
      difference: e.key,
    }
    this.seldata(param);
  };
  render() {
    const paginationProps = {
      showSizeChanger: true,
      total: this.state.total, // 数据总数
      pageSize: parseInt(this.state.pagesize), // 每页条数
      current: parseInt(this.state.page), // 当前页码
      pageSizeOptions: ["10", "20", "30", "100"],
      showTotal: ((total) => {
        return `共 ${total} 条`;
      }),
    };
    let listcolumns = [];

    if (this.state.queryshowfielddata.fieldsshow !== undefined) {
      (this.state.queryshowfielddata.fieldsshow || []).map(item => {
        let items = this.state.queryshowfielddata.fieldsall.filter((p) => {
          return p.key === item;
        });
        if (items.length > 0) {
          listcolumns.push({
            title: items[0].title,
            dataIndex: item,
            key: item,
            sorter: (a, b) => a[item] > b[item] ? 1 : -1
          })
        }
        return item;
      }
      );
    }
    listcolumns.push({
      title: '操作',
      key: 'action',
      render: (record) => (
        <span>
          <Button size="small" onClick={() => this.handleactivityshow(record)}>
            跟进信息
          </Button>&nbsp;&nbsp;
          <Button size="small">
            <Router history={customHistory}>
              <Link to={`/project/new/employee/${record.projectid}`} >编辑</Link>
            </Router>
          </Button> &nbsp;&nbsp;
          {this.state.difference==="2" &&(<Button size="small" >
            <a className="clickable" onClick={() => this.handleCheck(record)}>{record.status === 0 ? "审核" : (record.status === 1 ? "审核中" : "已审核")}</a>
          </Button>)}
        </span>
      ),
    });
    return (
      <ConfigProvider locale={zhCN}>
        <div style={{ width: "400px", height: "60px" }}>
          <div style={{ width: "20px", height: "50px", float: "left" }}>
          </div>
          <div style={{ width: "50px", height: "50px", float: "left" }}>
            <img src="/static/images/projectlist.png" alt="HR" loading="lazy" />
          </div>
          <div style={{ width: "320px", height: "30px", float: "left" }}>
            <h3 style={{ margin: "7px", padding: "0" }}>{"关联人员项目列表"}</h3>
          </div>
        </div>
        <Layout>
          <Layout style={{ padding: '0 24px 24px' }}>
            {this.state.showall && (<><Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                状态:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.bytstatus}
                  onChange={value => {
                    localStorage.setItem("projecttoolbarbytstatus", value);
                    this.setState({ bytstatus: value });
                  }}
                  placeholder="状态"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                  {(this.state.projectstatusdata || []).map(item => (
                    <AutoComplete.Option key={item.key} value={item.key}>{item.key}</AutoComplete.Option>
                  ))}
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                证书:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.certificate}
                  onChange={value => {
                    localStorage.setItem("projecttoolbarcertificate", value);
                    this.setState({ certificate: value });
                  }}
                  placeholder="证书"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                  {(this.state.employeecertificatedata || []).map(item => (
                    <AutoComplete.Option key={item.key} value={item.key}>{item.key}</AutoComplete.Option>
                  ))}
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                地区:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.location}
                  onChange={value => {
                    localStorage.setItem("projecttoolbarlocation", value);
                    this.setState({ location: value });
                  }}
                  placeholder="地区"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                  {(this.state.employeeareadata || []).map(item => (
                    <AutoComplete.Option key={item.key} value={item.key}>{item.key}</AutoComplete.Option>
                  ))}
                </AutoComplete>
              </Col>
            </Row>
            <Row style={{ marginBottom: 5 }}>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  单位名称:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={this.state.strcustomername}
                    onChange={value => {
                      localStorage.setItem("projecttoolbarstrcustomername", value);
                      this.setState({ strcustomername: value });
                    }}
                    placeholder="手机"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                  </AutoComplete>
                </Col>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  联系人:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={this.state.representative}
                    onChange={value => {
                      localStorage.setItem("projecttoolbarrepresentative", value);
                      this.setState({ representative: value });
                    }}
                    placeholder="身份证号"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                  </AutoComplete>
                </Col>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  社保地区:</div></Col>
                <Col span={6}>
                  <AutoComplete
                    style={{ width: "100%" }}
                    value={this.state.area}
                    onChange={value => {
                      localStorage.setItem("projecttoolbararea", value);
                      this.setState({ area: value });
                    }}
                    placeholder="社保地区"
                    filterOption={(inputValue, option) =>
                      option.value.indexOf(inputValue) !== -1}>
                    {(this.state.employeeareadata || []).map(item => (
                      <AutoComplete.Option key={item.key} value={item.key}>{item.key}</AutoComplete.Option>
                    ))}
                  </AutoComplete>
                </Col>
              </Row>
              <Row style={{ marginBottom: 5 }}>
                <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                  跟进日期:</div></Col>
                <Col span={6}>
                  <DatePicker.RangePicker
                    locale={locale}
                    style={{ width: "100%" }}
                    value={this.state.genjindate}
                    onChange={value => {
                      this.setState({
                        genjindate: value,
                      });
                    }}
                    placeholder="跟进日期"
                    autoFocus
                  />
                </Col>
              </Row></>)}
            <Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                项目编码:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.code}
                  onChange={value => {
                    localStorage.setItem("projecttoolbarcode", value);
                    this.setState({ code: value });
                  }}
                  placeholder="项目编码"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                项目名称:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.name}
                  onChange={value => {
                    localStorage.setItem("projecttoolbarname", value);
                    this.setState({ name: value });
                  }}
                  placeholder="项目名称"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={8}>
                <Divider type="vertical" />
                <Button type="primary" onClick={() => this.handlesel(1)} >
                  <i className="fa fa-search m-r-5" />
                  查询
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => this.handleclear()} >
                  清空
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => { this.setState({ showall: !this.state.showall }); }} >
                  {this.state.showall && (<UpOutlined />)}
                  {!this.state.showall && (<DownOutlined />)}
                  {this.state.showall ? '默认' : '更多'}
                </Button>
              </Col>
            </Row>
            <Row style={{ marginBottom: 5 }}>
              <Col span={10}>
                <Button type="primary" >
                  <i className="fa fa-plus m-r-5" />
                  <a href="project/new/0" style={{ color: "white" }}>新增</a>
                </Button>
                <Divider type="vertical" />
                <Dropdown
                  trigger={["click"]}
                  overlay={
                    <Menu>
                      {currentUser.hasPermission("ryexcelout") && (
                        <Menu.Item key="change-item-out">
                          <a onMouseUp={() => this.handlesel(2)}>EXCEL导出</a>
                        </Menu.Item>)}
                      {currentUser.hasPermission("ryexcelout") && (<Menu.Divider />)}
                      {currentUser.hasPermission("fieldshow") && (
                        <Menu.Item key="delete-item">
                          <a onMouseUp={() => this.handlefieldshow()}>显示隐藏列</a>
                        </Menu.Item>
                      )}
                    </Menu>
                  }>
                  <Button type="primary" style={{ margin: "10px" }} data-test="CreateButton" >
                    <AppstoreFilled />更多功能
                  </Button>
                </Dropdown>
              </Col>
            </Row>
            <Menu onClick={this.tabsClick} selectedKeys={this.state.difference} mode="horizontal">
              <Menu.Item key="1">{"未关联人员"}</Menu.Item>
              <Menu.Item key="2">{"已关联人员"}</Menu.Item>
            </Menu>
            <div>
              <Table rowKey='id'
                rowClassName={(record, index) => getRowClassName(record, index)}
                rowSelection={this.rowSelection()}
                columns={listcolumns}
                scroll={{ x: 'max-content' }}
                dataSource={this.state.data}
                pagination={paginationProps}
                loading={this.state.loading}
                onChange={this.handleTableChange}
              />
            </div>
          </Layout>
        </Layout>
      </ConfigProvider>
    );
  }
}

routes.register(
  "ProjectToolBar.List",
  routeWithUserSession({
    path: "/projecttoolbar",
    title: "关联人员项目",
    render: pageProps => <ProjectToolBar {...pageProps} difference="1" />,
  })
);
routes.register(
  "ProjectToolBar1.List",
  routeWithUserSession({
    path: "/projecttoolbarun",
    title: "已关联人员项目",
    render: pageProps => <ProjectToolBar {...pageProps} difference="2" />,
  })
);